<?php
namespace api\modules\mp\controllers;

use api\modules\mp\models\Comment;
use yii\web\Controller;
use Yii;
use yii\web\Response;

class CommentController extends Controller {

    public $enableCsrfValidation = false;

    public function behaviors() {
        return array_merge(parent::behaviors(), [
            [
                'class' => 'yii\filters\auth\QueryParamAuth',
                'tokenParam' => 'session',
            ],
        ]);
    }

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function actionIndex() {
        $type = Yii::$app->request->get('type', Comment::TYPE_COMPANION);
        $resourceId = Yii::$app->request->get('resourceId');
        $offset = Yii::$app->request->get('offset', 0);
        $size = Yii::$app->request->get('size');
        $res = Comment::getList([
            'type' => $type,
            'resource_id' => $resourceId,
            'pid' => 0,
        ], '*', 'ctime DESC', $offset, $size);
        $ids = array_column($res, 'id');
        $replies = [];
        if ($ids) {
            $ids = implode(',', $ids);
            $replies = Comment::getList("pid IN ($ids)");//todo 考虑数量限制
        }
        $list = [];
        foreach ($res as $k => $v) {
            $list[$v['id']] = $v + ['replies' => []];
        }
        foreach ($replies as $reply) {
            $list[$reply['pid']]['replies'][] = $reply;
        }
        return [
            'code' => 200,
            'data' => ['list' => array_values($list)]
        ];
    }

    /**
     * 评论/回复
     */
    public function actionPublish() {
        $data = Yii::$app->request->post();
        $data['openid'] = Yii::$app->user->getIdentity()->openid;
        $model = new Comment();
        $model->load($data, '');
        if ($model->validate()) {
            $model->save();
            return [
                'code' => 200,
                'data' => [
                    'id' => $model->id,
                    'info' => $model->info()
                ],
            ];
        } else {
            return [
                'code' => 401,
                'msg' => current($model->getFirstErrors()),
                'field' => key($model->getFirstErrors())
            ];
        }
    }
}
